package cn.tedu.yushougeproduct.service.impl;


import cn.tedu.yushouge.commons.ex.ServiceException;
import cn.tedu.yushouge.commons.web.ServiceCode;
import cn.tedu.yushougeproduct.mapper.CategoryMapper;
import cn.tedu.yushougeproduct.pojo.entity.Category;
import cn.tedu.yushougeproduct.pojo.param.CategoryAddNewParam;
import cn.tedu.yushougeproduct.pojo.param.CategoryUpdateInfoParam;
import cn.tedu.yushougeproduct.pojo.vo.CategoryListItemVO;
import cn.tedu.yushougeproduct.pojo.vo.CategoryStandardVO;
import cn.tedu.yushouge.commons.pojo.vo.PageData;
import cn.tedu.yushougeproduct.service.ICategoryService;
import cn.tedu.yushouge.commons.util.PageInfoToPageDataConverter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void addNew(CategoryAddNewParam categoryAddNewParam) {
        log.debug("开始处理【添加商品分类】的业务，参数：{}", categoryAddNewParam);

        // 检查商品分类名称是否被占用，如果被占用，则抛出异常
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name", categoryAddNewParam.getCategoryName());
        int countByName = categoryMapper.selectCount(queryWrapper);
        log.debug("根据商品分类名称统计匹配的商品分类数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "添加商品分类失败，商品分类名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        // 将商品分类数据写入到数据库中
        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewParam, category);
        category.setGmtCreate(LocalDateTime.now());
        log.debug("准备将新的商品分类数据写入到数据库，数据：{}", category);
        int rows = categoryMapper.insert(category);
        if (rows != 1){
            String message = "添加商品分类失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的商品分类数据插入到数据库，完成！");
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据ID删除商品分类】的业务，参数：{}", id);
        // 检查商品分类是否存在，如果不存在，则抛出异常
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = categoryMapper.deleteById(id);
        if (countById == 0) {
            String message = "删除商品分类失败，商品分类不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        log.debug("从商品分类表删除一条数据，完成！");
    }

    @Override
    public void updateInfoById(Long id, CategoryUpdateInfoParam categoryUpdateInfoParam) {
        log.debug("开始处理【根据ID修改商品分类数据】的业务，参数：{}", id);

        // 检查商品分类是否存在，如果不存在，则抛出异常
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = categoryMapper.selectCount(queryWrapper);
        log.debug("根据商品分类ID统计匹配的商品分类数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改商品分类详情失败，商品分类数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查商品分类名称是否被其它商品分类占用，如果被占用，则抛出异常
        QueryWrapper<Category> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("category_name", categoryUpdateInfoParam.getCategoryName())
                .ne("id", id);
        int countByName = categoryMapper.selectCount(queryWrapper2);
        log.debug("根据商品分类名称统计匹配的商品分类数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改商品分类详情失败，商品分类名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateInfoParam,category);
        category.setId(id);
        category.setGmtModified(LocalDateTime.now());
        int rows = categoryMapper.updateById(category);
        if (rows == 0) {
            String message = "修改商品分类失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的商品分类数据更新入到数据库，完成！");
    }

    @Override
    public CategoryStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询商品分类详情】的业务，参数：{}", id);
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        if (queryResult == null){
            String message = "查询商品分类详情失败，商品分类数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<CategoryListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<CategoryListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询商品分类列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<CategoryListItemVO> list = categoryMapper.list();
        PageInfo<CategoryListItemVO> pageInfo = new PageInfo<>(list);
        PageData<CategoryListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public void setEnable(Long id) {
        log.debug("开始处理【启用类别】的业务，参数：{}", id);
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理【禁用类别】的业务，参数：{}", id);
        updateEnableById(id, 0);
    }

    private void updateEnableById(Long id , Integer enable){
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);

        if (currentCategory == null) {
            String message = ENABLE_TEXT[enable] + "类别失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if (currentCategory.getEnable() == enable) {
            String message = ENABLE_TEXT[enable] + "类别失败，此类别已经处于" + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Category updateCategory = new Category();
        updateCategory.setId(id);
        updateCategory.setEnable(enable);

        int rows = categoryMapper.updateById(updateCategory);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void setDisplay(Long id) {
        log.debug("开始处理【显示类别】的业务，参数：{}", id);
        updateDisplayById(id, 1);
    }

    @Override
    public void setHide(Long id) {
        log.debug("开始处理【隐藏类别】的业务，参数：{}", id);
        updateDisplayById(id, 0);
    }

    private void updateDisplayById(Long id , Integer display){
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);

        if (currentCategory == null) {
            String message = DISPLAY_TEXT[display] + "类别失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if (currentCategory.getIsDisplay() == display) {
            String message = DISPLAY_TEXT[display] + "类别失败，此类别已经处于" + DISPLAY_TEXT[display] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Category updateCategory = new Category();
        updateCategory.setId(id);
        updateCategory.setIsDisplay(display);

        int rows = categoryMapper.updateById(updateCategory);
        if (rows != 1) {
            String message = DISPLAY_TEXT[display] + "类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

}
